/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

package com.chinamobile.cmss.lakehouse.common.dto;

import java.security.InvalidParameterException;

import javax.validation.constraints.Min;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

@AllArgsConstructor
@NoArgsConstructor
@ApiModel
@Data
public class SearchMetadataTableDto {
    @Min(value = 1, message = ">1")
    @ApiModelProperty("page number")
    private Integer pageNo = 1;

    @Min(value = 1, message = ">1")
    @ApiModelProperty("页面大小")
    private Integer pageSize = 10;

    @ApiModelProperty("table name")
    private String tableName;

    @ApiModelProperty("database name")
    private String databaseName;

    @ApiModelProperty(value = "reference task", allowableValues = "SQL, Data Sync, Metadata Explore")
    private String refTaskType;

    @ApiModelProperty("reference task id")
    private String refTaskId;

    @ApiModelProperty(value = "yyyy-MM-dd")
    private String[] lastModifyTime;

    private Integer[] seconds;

    public Integer[] toSeconds() {
        if (lastModifyTime == null || lastModifyTime.length == 0) {
            return null;
        } else {
            final int modifyTimeSize = 2;
            if (lastModifyTime.length != modifyTimeSize && lastModifyTime.length != 0) {
                throw new InvalidParameterException("lastModifyTime size must be 0 or 2");
            } else if (seconds == null) {
                // example: 2021-04-29
                String format = "yyyy-MM-dd";
                seconds = new Integer[2];
                DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
                seconds[0] = (int) (formatter.parseDateTime(lastModifyTime[0]).getMillis() / 1000);
                // add offset, in order to search next day data
                seconds[1] = (int) (formatter.parseDateTime(lastModifyTime[1])
                    .plusHours(23)
                    .plusMinutes(59)
                    .plusSeconds(59)
                    .getMillis() / 1000);
            }
        }
        return seconds;
    }
}
